package com.apes.fico.finance.respository;

import com.apes.fico.finance.model.gl.InitBalance;
import com.apes.framework.jpa.repository.CustomRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;
import java.util.Map;

public interface InitBalanceRepository extends CustomRepository<InitBalance, String> {
    InitBalance findByCompany_IdAndPeriodAndAccountingOperatingChart_Id(String company, int period, String accId);

    @Query("select new map(T.id as id,T.accountingOperatingChart.code as code,T.openingBalance as openingBalance) from InitBalance T where 1=1 and(T.company.id =:company and T.year=:year)")
    List<Map<String, String>> findAllByCompanyAndYear(@Param("company") String company, @Param("year") int year);

    @Query("select new map(T.id as id,T.accountingOperatingChart.code as code,T.accountingOperatingChart.balanorient as balanorient," +
            "T.openingBalance as openingBalance,T.credit as credit,T.debit as debit)" +
            " from InitBalance T where 1=1 and(T.company.id =:company and T.year=:year)" +
            " and(T.accountingOperatingChart.code=:accountCode)")
    Map<String, String> findAllByCompanyAndYearAndAccountCode(@Param("company") String company, @Param("accountCode") String accountCode, @Param("year") int year);

    @Query("select new map(T.id as id,T.accountingOperatingChart.code as code,T.accountingOperatingChart.balanorient as balanorient," +
            "T.openingBalance as openingBalance,T.credit as credit,T.debit as debit)" +
            " from InitBalance T where 1=1 and (T.company.id=:company)and (T.year between :year and :stopYear)")
    List<Map<String, Object>> findByCompanyAndYear(@Param("company") String company, @Param("year") int year, @Param("stopYear") int stopYear);

    @Query("select new map(T.id as id,T.accountingOperatingChart.code as code,T.accountingOperatingChart.balanorient as balanorient," +
            "T.openingBalance as openingBalance,T.credit as credit,T.debit as debit)" +
            " from InitBalance T where 1=1 and(T.company.id =:company and (T.year between :year and :stopYear))" +
            " and(T.accountingOperatingChart.code=:accountCode)")
    List<Map<String, Object>> findAllByCompanyAndBetwennYearAndAccountCode(@Param("company") String company, @Param("accountCode") String accountCode, @Param("year") int year, @Param("stopYear") int stopYear);

    //批量更新期初余额为0
    @Modifying
    @Query(value = "update InitBalance t set t.openingBalance = 0 where t.period = :period and t.company.id = :company")
    void updateOpenBalanceByPeriodAndCompany_Id(int period, String company);
}
